#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <time.h>

#include "utils.h"

	

//static int compare_sequences(const SEQUENCE *seq1, const SEQUENCE *seq2) {
static int compare_sequences(const void *pseq1, const void *pseq2) {
	int i;
	SEQUENCE *seq1 = *(SEQUENCE * const *)pseq1;
	SEQUENCE *seq2 = *(SEQUENCE * const *)pseq2;
	
	//printf("%s %s\n", seq2string(seq1),seq2string(seq2));
	int minl = MIN(seq1->real_length,seq2->real_length);
	
	for (i = 0; i < minl; i++) {
		//printf("%u %u\n",seq1->bitseq[i], seq2->bitseq[i]);
		if ( seq1->bitseq[i] > seq2->bitseq[i]) {
			return 1;			
			} 
		else if (seq1->bitseq[i] < seq2->bitseq[i]) {
			return -1;
			}
		}
	return seq1->real_length - seq2->real_length;
	}


int main (int argc, char **argv) {
	int total_sequences, total_bitseq_length;
	SEQUENCE **seqs = NULL;
	SEQUENCE *seqdata = NULL;
	WORD *bitseqdata = NULL;

	fprintf(stderr, "word size: %d \n", sizeof(WORD));
	if (argc != 3) {
		fprintf(stderr, "usage: %s fasta_file output_file\n", argv[0]);	
		return 1;
		}
	fasta2seq(argv[1], &seqs, &seqdata, &bitseqdata, &total_sequences, &total_bitseq_length);
	if (seqs == NULL) {
		return 1;
		}
	//fprintf(stderr, "Number of sequences: %d\n", total_sequences);

	start_watch();	
	fprintf(stderr, "sorting sequences\n");
	
	qsort(seqs, total_sequences, sizeof(SEQUENCE *), compare_sequences);
	
	fprintf(stderr, "sorting finished | ");
	stop_watch();
	
	start_watch();	
	fprintf(stderr, "outputting sequences\n");
	
	FILE *output = fopen(argv[2],"wb");
	if(output == NULL) {
		fprintf(stderr,"can't open output file: %s.\n", argv[2]);
		return 1;
	}
	
	// dump the total number of sequences
	fwrite(&total_sequences ,sizeof (int) , 1, output);
	fwrite(&total_bitseq_length ,sizeof (int) , 1, output);
	int i;
	//char charseq[MAXLINE] = {0};
	for(i = 0; i < total_sequences; i++) {
		
		//char charseq[MAXLINE]= {0};
		//bitseq2char(seqs[i]->bitseq, seqs[i]->real_length, charseq);
		//printf(">%ld\n%s\n", seqs[i]->id, charseq);		
		
		
		fwrite(&seqs[i]->id, sizeof(long),1 ,output);
		fwrite(&seqs[i]->real_length, sizeof(int),1 ,output);
		
		fwrite(seqs[i]->bitseq, sizeof(WORD), blen(seqs[i]->real_length) ,output);
		
	}
	
	fclose(output);
	fprintf(stderr, "outputting finished | ");
	stop_watch();
	
	
	/*
	
	for (i = 0; i < N; i++) {
		free(seqs[i]);
	} 
	free(seqs);
	*/
	return 0;
	}
